<template>
	<view class="">
		<view class="search-box">
			<u-search placeholder="请输入项目名称" shape="square" :showAction="false" v-model="searchData.name" @search="onSearch"></u-search>
		</view>
		<view class="my-list mt-20 bg-white">
			 <u-list :height="swiperHeight" @scrolltolower="scrolltolower">
				 
				<u-checkbox-group 
					v-if="selectType === '1'"
					v-model="checkeds" 
					iconPlacement="right" 
					placement="column"
					activeColor="#e54d42"
					:borderBottom="true" 
					@change="checkboxChange">
					<u-checkbox 
						v-for="(proIm, proIx) in dataList" 
						:key="proIm.id" 
						:label="proIm.name"
						:name="proIm.id"
						shape="circle"
						:customStyle="{padding: '20rpx'}">
					</u-checkbox>
				</u-checkbox-group>
				
				<view class="" v-if="selectType === '2'">
					<view class="sety-num" v-for="(proIm, proIx) in dataList" :key="proIx">
						<image class="img" :src="proIm.image || '../../static/logo.png'" />
						<view class="tbx">
							<text>{{proIm.name}}</text>
							<view class="flex justify-between align-center">
								<view class="line-red">
									<text class="fsize-22">￥</text>
									<text class="fsize-32">{{proIm.price}}</text>
								</view>
								<u-number-box
									v-model="proIm.nums"
									step="1"
									button-size="26"
									:min="0"
									:showMinus="proIm.nums > 0">
									<view
										slot="input"
										style="width: 50px;text-align: center;"
										class="input"
									>
										<text v-if="proIm.nums > 0">{{proIm.nums}}</text>
									</view>
								</u-number-box>
							</view>
						</view>
					</view>
				</view>
				
				<view v-if="selectType === '3'">
					<view
						class="client-list-item flex justify-between align-center mb-20" 
						v-for="(item, index) in dataList" :key="index"
						@click="onProject(item)">
						<text>{{item.name}}</text>
						<uni-icons 
							custom-prefix="iconfont" 
							:type="item.selected?'icon-checkbox-square-fill':'icon-checkbox-square'" 
							:color="item.selected?'#e54d42':'#666'"
							size="34">
						</uni-icons>
					</view>
				</view>
				
			</u-list>
		</view>
		<!-- 无数据时默认显示 -->
		<view class="emptybox" v-if="dataList.length === 0">
			<u-empty icon-size="150" text="暂无数据" mode="data"></u-empty>
		</view>
		<u-gap height="80" v-if="selectType!=='3'"></u-gap>
		<view class="bottom-button" v-if="selectType!=='3'">
			<u-button type="primary" size="large" color="#e54d42" text="确认选择" @click="onNavigateBack"></u-button>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import listHeightMixin from '@/common/computedAltitude.js'
	export default {
		mixins:[listHeightMixin],
		data() {
			return {
				selectType: '1', // 1选择卡项类型 ， 2选择开单类型 3选择可服务项目
				loadmore: {
					status: 'loadmore',
					iconType: 'flower',
					loadText: {
						loadmore: '轻轻上拉',
						loading: '努力加载中',
						nomore: '实在没有了'
					},
				},
				searchData: {
					name: '',
					page: 1,
					limit: 999,
					staffId: 0,
				},
				dataList: [],
				checkeds: [],
				newCheckeds:[],
				nels:[],
			}
		},
		onLoad(options) {
			this.selectType = options.type
			if(options.type === '1' && options.items){
				this.checkeds = JSON.parse(options.items).map(im=> im.projectId)
			}else if(options.type === '2' && options.items){
				this.nels = JSON.parse(options.items)
			} else if(options.type === '3'){
				this.searchData.staffId = options.staffId
			}
			this.getPageList()
		},
		methods: {
			mergeArr(arr1, arr2){
				const combined = arr1.concat(arr2);
				const dict = combined.reduce((acc, {id, nums, ...rest}) => {
				  acc[id] = acc[id] || {id, nums: 0,  ...rest};
				  acc[id].nums += nums;
				  return acc;
				}, {});
				const result = Object.values(dict);
				return result
			},
			newArr(arr1, arr2){
				const map = new Map(arr1.map(item => [item.itemId, item])) // 将 arr1 转换为 Map
				arr2.forEach(item => {
				  const existing = map.get(item.itemId)
				  if (existing) {
				    map.set(item.itemId, { ...existing, ...item }) // 如果存在，则用第二个数组中的元素替换第一个数组中的元素
				  }
				})
				const result = [...map.values()] // 将 Map 中的值转换为数组
				return result
			},
			onProject(row){
				row.selected = !row.selected
				this.$reqJsonPost('GetProjectsDoSetSelected', {... row, staffId: this.searchData.staffId}).then(res=>{
					uni.$emit('upList', 2)
				})
			},
			checkboxChange(arr) {
				this.newCheckeds = arr
			},
			onNavigateBack(){
				if(this.selectType==='1'){
						if(this.newCheckeds.length > 0){
						let pros = this.dataList.filter(im=>this.newCheckeds.includes(im.id))
						pros = pros.map(im=>{
							return {
								projectId: im.id,
								manualPercentageType: 1,
								manualPercentage: 0,
								times: 0,
								projectObj: im
							}
						})
						uni.$emit('event-pros', pros)
						uni.navigateBack()
					}else {
						uni.showToast({
							title: '请选择项目',
							icon: 'none',
							duration: 2000
						})
					}
				}else if(this.selectType==='2'){
					const newArr = this.dataList.filter(om=>om.nums !== 0).flatMap(({nums, ...rest}) => {
						return Array.from({length: nums}, () => ({...rest, nums: 1}));
					});
					if(newArr.length > 0){
						uni.$emit('add-pct', newArr)
						uni.navigateBack()
					}else {
						uni.showToast({
							title: '请选择开单项目',
							icon: 'none',
							duration: 2000
						})
					}
				}
				// else if(this.selectType==='3'){
				// 	this.$reqJsonPost('GetProjectsDoBatchEdit', {id: this.searchData.staffId, data: this.newCheckeds}).then(res=>{
				// 		this.$refs.uToast.show({
				// 			message: res.msg,
				// 			complete(){
				// 				uni.$emit('upList', 2)
				// 				uni.navigateBack()
				// 			}
				// 		})
				// 	})
				// }
			},
			// 搜索事件
			onSearch() {
				this.searchData.page = 1
				this.dataList = []
				this.getPageList()
			},
			getPageList() {
				this.$reqPost(this.selectType==='3'?'GetProjectsPageList':'CoreCmsProjectList', this.searchData).then(res => {
					let list = this.selectType==='3'?res.data:res.data.map(im=>{
						im.nums = 0
						im.staffName = ''
						im.staffId = 0
						im.salerName = ''
						im.salerId = 0
						im.appointmentTime = ''
						im.itemId = im.id
						return im
					})
					this.dataList = [...this.dataList, ...list]
					if(this.selectType==='2'){
						this.dataList = this.mergeArr(this.dataList, this.nels)
					}
					// if(this.selectType==='3'){
					// 	this.checkeds = this.dataList.filter(im=>im.select === 1).map(jm=>{
					// 		return jm.id
					// 	})
					// }
					if (res.count > this.dataList.length) {
						this.loadmore.status = 'loadmore'
						this.searchData.page++
					} else {
						// 数据已加载完毕
						this.loadmore.status = 'nomore'
					}
				})
			},
			scrolltolower() {
				if (this.loadmore.status === 'loadmore') {
					this.getPageList()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.item {
		padding: 20rpx;
		font-size: 28rpx;
		border-bottom: 1px #f5f5f5 solid;
	}
	.sety-num{
		padding: 20rpx;
		display:flex;
		border-bottom: 1px #f7f7f7 solid;
		.img{
			width: 100rpx;
			height: 100rpx;
			border-radius: 10rpx;
			flex-shrink: 0;
			margin-right: 10px;
		}
		.tbx{
			width: 100%;
			display:flex;
			flex-direction: column;
			justify-content: space-between;
		}
	}
</style>
